from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .serializer import *

class Login(APIView):
    def post(self,request):
        name=request.POST.get('name')
        password=request.POST.get('password')
        user_obj=models.Users.objects.filter(name=name).first()
        if user_obj:
            if user_obj.password==password:
                return Response({'msg':'登录成功','code':1000,'user_id':user_obj.id,'user':user_obj.name})
            else:
                return Response({'msg':'用户名或密码错误','code':1001})
        else:
            return Response({'msg': '登录失败', 'code': 1002})

class ShowProduct(APIView):
    def get(self,request):
        product=models.Product.objects.all()
        obj=ProductModelSerializer(product,many=True)
        return Response(obj.data)

class AddOrder(APIView):
    def post(self,request):
        obj=OrderModelSerializer(data=request.data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({'msg': '成功', 'code': 1000})
            return Response({'msg': '失败', 'code':1001})

class ShowOrder(APIView):
    def get(self,request,uid):
        order=models.Order.objects.filter(name=uid)
        obj=OrderModelSerializer(order,many=True)
        return Response(obj.data)
